package com.mseiferle.mediabrowser.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONException;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONValue;

/**
 * @author michael Returns a JAVA value from JSON data.
 */
class GetJSONValue {
	/**
	 * The URL to geht the JSON Object from.
	 */
	private String url;
	/**
	 * The returned string.
	 */
	private JSONValue jsonValue;

	/**
	 * the parent object.
	 */
	private Htmlmediabrowser p;

	
	/**
	 * @param htmlp Url to get the JSON ressource.
	 * @param jsonUrl media browser object.
	 */
	GetJSONValue(final Htmlmediabrowser htmlp, final String jsonUrl) {
		this.p = htmlp;
 		url = jsonUrl;
		url = URL.encode(url);

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);

		try {
			@SuppressWarnings("unused")
			Request request = builder.sendRequest(null, new RequestCallback() {
				public void onError(final Request request,
						final Throwable exception) {
					GWT.log("Couldn't retrieve JSON", null);
				}

				public void onResponseReceived(final Request request,
						final Response response) {
					if (Constants.HTTP200 == response.getStatusCode()) {
						try {
							// parse the response text into JSON
							jsonValue = JSONParser.parse(response.getText());
							JSONArray jsonArray = jsonValue.isArray();

							if (jsonArray != null) {
								p.setJSONValue(jsonArray);
							} else {
								throw new JSONException();
							}
						} catch (JSONException e) {
							GWT.log("Could not parse JSON", e);
						}
					} else {
						GWT.log("Couldn't retrieve JSON ("
								+ response.getStatusText() + ")", null);
					}
				}
			});
		} catch (RequestException e) {
			GWT.log("Couldn't retrieve JSON", null);
		}
	}

}
